import Vue from 'vue'
import Vuex from 'vuex'
import rq from '../../requests'
import qs from 'qs'
import { Notify } from 'vant';
Vue.use(Vuex)

export default {
  namespaced: true,
  state: {
    imageList: [],
    hashToUrl: {}
  },
  mutations: {
    setImageList(state, { newImageList }) {
      state.imageList = newImageList;
    },
    updateHashToUrl(state, { hash, url }) {
      console.log("updateHashToUrl");
      console.log("hash: " + hash + ", url: " + url);
      state.hashToUrl[hash] = url;
      let hashToUrl = state.hashToUrl;
      console.log(hashToUrl);
      state.hashToUrl = {...hashToUrl};
    }
  },
  getters: {
    getImageList: (state) => {
      console.log("Enter getImageList");
      return state.imageList;
    },
    imageCount: (state) => {
      let count = Object.keys(state.hashToUrl).length;
      console.log("Enter imageCount, count: " + count);
      return count;
    },
    hashToUrl: (state) => {
      return state.hashToUrl;
    },
    mapHashToUrl: (state) => {
      return (hash) => {
        console.log("Enter mapHashToUrl innerFunc");
        return state.hashToUrl[hash];
      };
    }
  },
  actions: {
    uploadImage({ commit, state, rootState, dispatch }, { nickName, file }) {
      console.log("Enter uploadImage");
      console.log(file);
      let formData = new FormData();
      let groupToken = rootState.group.selectedGroupToken || "";
      formData.append('file', file.file);
      formData.append('groupToken', groupToken);
      formData.append('nickName', nickName);

      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      };
      rq.requests.post("/fic/pic/upload", formData, config)
      .then(({ eCode, res, eMessage }) => {
        if (!eCode) {
          dispatch("listImage", {})
          Notify({ type: 'info', message: "上传成功" });
          return;
        }
      });
    },
    downloadImage({ commit, state, rootState, dispatch }, { fileHash }) {
      console.log("Enter downloadImage")
      console.log("fileHash: " + fileHash)
      let body = {
        "fileHash": fileHash
      };
      if(state.hashToUrl[fileHash] != null) {
        return;
      }
      rq.requests.post("/fic/pic/download", qs.stringify(body), {
        responseType: "blob"
      })
        .then(({ eCode, res, eMessage }) => {
          if (!eCode) {
            let bytes = res;
            let url = window.URL.createObjectURL(bytes);
            commit("updateHashToUrl", {
              hash: fileHash,
              url: url
            });
            return;
          }
        });
    },
    mapHashToUrlWait({ commit, state, rootState, dispatch }, { fileHash }) {
      console.log("Enter mapHashToUrlWait ");
    },
    listImage({ commit, state, rootState, dispatch }, {  }) {
      let groupToken = rootState.group.selectedGroupToken;
      console.log("Enter listImage ,groupToken: ", groupToken);
      let body = {
        "groupToken": groupToken
      };
      rq.requests.post("/fic/pic/list", qs.stringify(body))
        .then(({ eCode, res, eMessage }) => {
          if (!eCode) {
            console.log("Enter listImage result, res: ");
            console.log(res);
            let imageList = res || [];
            commit("setImageList", {
              newImageList: imageList
            });
            for (let imageDto of imageList) {
              console.log(imageDto);
              let fileHash = imageDto.fileHash;
              dispatch("downloadImage", { fileHash: fileHash });
            }
            return;
          }
          Notify({ type: 'danger', message: eMessage });
        });
    },
    deleteImage({ commit, state, rootState, dispatch }, { fileHash }) {
      let groupToken = rootState.group.selectedGroupToken;
      let body = {
        "groupToken": groupToken,
        "fileHash": fileHash
      };
      rq.requests.post("/fic/pic/remove", qs.stringify(body))
        .then(({ eCode, res, eMessage }) => {
          if (!eCode) {
            dispatch("listImage", {})
            Notify({ type: 'info', message: "删除成功" });
            return;
          }
          Notify({ type: 'danger', message: eMessage });
        });
    }
  }
}